const API_HOST = "https://bbs.zzbrainy.com"
const Auth = require('./auth')
const Upload = require('./cloud')
const AuthKEY = "LpkkxTSIFGZj9z3lkrAIVxFMFu8A0oVUpmM6B7FSwfA="

/*
 * 丸子小程序版本：Ver 1.0.8                                                                        
 * WordPress 小程序社区版 - UI ： 波波 / Pluigns : 艾码汇 / Marking : M主题@爱折腾的Kit
 * 一款基于 WordPress 网站后端的，采用 WordPress REST API 定制的小程序，做好看的微信小程序
 */
/*-------------------------------------------------------------------------------*/

const API = {}

API.getHost = function () {
  return API_HOST;
}

API.request = function (url, method = "GET", data = {}, args = {
  token: true,
  isPull: false,
  isCusUrl: false,
}) {

  return new Promise(function (resolve, reject) {

    wx.showNavigationBarLoading()
    if (!args.isCusUrl) {
      url = API_HOST + url;
    }

    if (args.token) {
      const token = API.token();
      if (token) {
        if (url.indexOf("?") > 0) {
          url = url + '&access_token=' + token;
        } else {
          url = url + '?access_token=' + token;
        }
      } else {
        console.warn('[提示]', '部分数据需要授权，检测出当前访问用户未授权登录小程序');
      }
    }


    wx.request({
      url: url,
      data: data,
      method: method,
      success: function (res) {
        if (res.statusCode == 200) {
          resolve(res.data);
        } else if (res.data.code === "rest_post_invalid_page_number") {
          wx.showToast({
            title: '没有更多内容',
            mask: false,
            duration: 1000
          });
        } else {
          reject(res.data);
        }
        wx.hideNavigationBarLoading()
      },
      fail: function (err) {
        wx.hideNavigationBarLoading();
        reject(err);
      }
    })
  });

}

API.get = function (url, data = {}, args = {
  token: false
}) {
  return API.request(url, "GET", data, args);
}

API.post = function (url, data, args = {
  token: true
}) {
  return API.request(url, "POST", data, args);
}

API.put = function (url, data, args = {
  token: true
}) {
  return API.request(url, "PUT", data, args);
}
API.delete = function (url, data, args = {
  token: true
}) {
  return API.request(url, "DELETE", data, args);
}

API.login = function () {
  return new Promise(function (resolve, reject) {
    if( Auth.check() ) {
			Auth.login()
			resolve( Auth.user() );
		} else {
			Auth.login().then( res => {
				resolve( res );
			}).catch( err =>{
				reject(err);
			})
		}
  });
}

API.getUser = function () {
  if (Auth.check()) {
    return Auth.user();
  } else {
    return false;
  }
}

API.logout = function () {
  getApp().globalData.user = null;
  wx.removeStorageSync('user');
  wx.removeStorageSync('token');
  wx.removeStorageSync('expired_in');
}

API.getProfile = function () {
  return new Promise(function (resolve, reject) {
    Auth.getUserInfo().then( data => {
      wx.showLoading({
        title: '登陆中',
      })
			API.post('/wp-json/mp/v2/user/login', data, { 
        token: false
      }).then( res => {
				//console.log( res );
				API.storageUser( res );
				resolve( res.user );
			}, err => {
				reject( err );
			});
		})
		.catch( err =>{
			//console.log( err );
			reject( err );
		})
  });
}

API.token = function () {
  let token = Auth.token();
  let datetime = Date.now();
  if (token && datetime < wx.getStorageSync('expired_in')) {
    return token;
  } else {
    //API.getUserInfo;
    return '';
  }
}

API.storageUser = function (res) {
  getApp().globalData.user = res.user;
  wx.setStorageSync('user', res.user);
	wx.setStorageSync('_USER_OPENID', res.openid);
	//wx.setStorageSync('_SESSION_KEY', res.session_key);
	if( res.unionid ) {
		wx.setStorageSync('_USER_UNIONID', res.unionid);
	  }
	if( res.access_token ) {
		wx.setStorageSync('token', res.access_token);
		wx.setStorageSync('expired_in', res.expired_in);
	}
}

/**
 * 需要授权的接口调用
 * @param	{Function} fn
 * @return {Promise}
 */
API.guard = function (fn) {
  const self = this
  return function () {
    if (API.getUser()) {
      return fn.apply(self, arguments)
    } else {
      return API.getUserInfo().then(res => {
        console.log('登录成功', res);
        return fn.apply(self, arguments)
      }, err => {
        console.log('登录失败', err);
        return err
      })
    }
  }
}

 /**
 * 上传文件至媒体库
 * @param	{Files} 
 * @return {Promise}
 */
API.upload = function(url, files = "", args = { token: true }) {
	return new Promise(function(resolve, reject) {
		url = API_HOST + url;
		if (args.token) {
			const token = API.token();
			if(token) {
				if(url.indexOf("?")>0) {
					url = url + '&access_token=' + token;
				} else {
					url = url + '?access_token=' + token;
				}
			} else {
				console.warn('[提示]','需要授权才能上传图片，检测出当前访问用户未授权登录小程序');
				wx.showModal({
					title: '温馨提示',
					content: '上传图片需要授权登录',
					success: function(res) {
						if (res.confirm) {
							API.getUserInfo()
						}
					}
				})
			}
		} else {
			console.warn('[提示]','需要授权才能上传图片');
			wx.showModal({
				title: '温馨提示',
				content: '上传图片需要授权登录'
			})
		}
		wx.uploadFile({
			url: url,
			filePath: files,
			name: 'media',
			success: function (res) {
				if (res.statusCode == 200) {
					let data = JSON.parse(res.data);
					if(data.status == 200) {
						console.log("上传成功")
						resolve(data);
					} else if(data.status == 500) {
						console.log(data.message)
						reject(data)
          }
          else if(data.status == 400) {
						console.log(data.message)
						reject(data)
					}
				} else {
					console.log("上传失败")
					reject(res.data)
				}
			},
			fail: function (err) {
				console.log(err)
				reject(err)
			}
		})
	})
}

API.media = function( filePath, data = {} ) {
	return new Promise(function(resolve, reject) {
		API.get('/wp-json/mp/v2/media', data, { token: true }).then(res => {
			if( res.status == 200 ) {
        console.log(res);
				if( res.option == 'qiniu' ) {
					Upload.qiniu( filePath, res.data ).then(success => {
						resolve(success)
					})
					.catch(fail =>{
						reject(fail)
					})
				} else if( res.option == 'aliyun' ) {
					Upload.aliyun( filePath, res.data ).then(success => {
						resolve(success)
					})
					.catch(fail =>{
						reject(fail)
					})
				} else if( res.option == 'tencent' ) {
					Upload.tencent( filePath, res.data ).then(success => {
						resolve(success)
					})
					.catch(fail =>{
						reject(fail)
					})
				} else {
					API.upload('/wp-json/mp/v2/media', filePath, { token: true }).then(success => {
						resolve(success)
					})
					.catch(fail =>{
						reject(fail)
					})
				}
			} else {
				reject(res)
			}
		})
		.catch( err =>{
			reject(err)
		})
	})
}

API.message = function () {
  return new Promise(function (resolve, reject) {
    let openid = wx.getStorageSync('_USER_OPENID')
		if( openid ) {
			API.get('/wp-json/mp/v2/message/notice', { openid: openid } ).then(res => {
        wx.setStorageSync('message', res);
				resolve( res );
			}, err => {
				reject( err );
			});
		}
  });
}

API.template = function () {
  return new Promise(function (resolve, reject) {
    API.get('/wp-json/mp/v2/subscribe/templates').then(res => {
      //console.log(res);
      if(res.status == 200) {
        wx.setStorageSync('templates', res.data);
      }
      resolve(res);
    }, err => {
      reject(err);
    });
  });
}

module.exports = API